<script setup>
import {
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { getToken } from "@/utils/auth";
import { onMounted, ref, watch, reactive } from 'vue'
import { useConfirm } from '@/hooks/useConfirm'
import { ElMessage } from 'element-plus';
import { getCurrentInstance } from 'vue';
import {applyPage,applyAdd,applyUpdate,applyDelete,applyPass,applyUnpass,applyPassBatch} from "@/api/stock/apply.js";
import {productAllService} from '@/api/stock/product'
import {batchstockListAll} from '@/api/stock/batchstock'

// 获取库存中的商品名称
const allProducts = ref([])
const allProduct = async() => {
  let r = await productAllService()
  console.log("data",r.data);
  allProducts.value = r.data
}
// 获取商品对应批次
const batches = ref([])
const allBatch = async()=>{
  console.log("222---",editModel.value.product);
  let r = await batchstockListAll({productsId:editModel.value.product})
  if(r.data.length == 0){
    alert('该商品无对应批次！')
  }
  console.log("batch",r.data);
  batches.value = r.data
}
// 获取商品对应批次下的数量
const showNums = ref({})
const selectNum = ref()
const allNums = async()=>{
  let r = await batchstockListAll({
    productsId:editModel.value.product,
    batchId:editModel.value.batchid
  })
  showNums.value = r.data[0]
  console.log('111111',r);
  const a = showNums.value.productsNum
  const b = showNums.value.productsUnqualified
  const c = showNums.value.productsApply
  selectNum.value = a-b-c
}

const { proxy } = getCurrentInstance();  //获取当前实例

//分页条数据模型
const pageNum = ref(1)//当前页
watch(pageNum, () => { loadData() })
const total = ref(20)//总条数
const pageSize = ref(5)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size;
  loadData();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num;
  loadData();
}


// 列表数据模型
const tableData = ref([])
const param = ref({
  pageNumber: 1,
  pageSize: 10,
  userid:'',
  product:'',
  flag:''
})
// 
/** 获取列表数据  */
const loadData = async () => {
  let r = await applyUnpass(param.value)
    console.log('aaa', r.data.items)
    total.value = r.data.total;
    tableData.value = r.data.items;  
}

onMounted(() => {
  loadData()
  allProduct()
  // allBatch()
})

// 审批数据
const title = ref('')
const editModel = ref({
  product: '',
  batchid:'',
  amount: '',
  flag:'',
  abc:''
})
const editModels = ref([])
// 同意
const changeData = ref({})
const showDialog = async(row) => {
  editModel.value.product = row.product;
  editModel.value.batchid = row.batchid;
  editModel.value.amount = row.amount;
  editModel.value.flag = 0
  editModel.value.id = row.id
 
  await allNums()
  console.log("wtwtwt",selectNum.value);
  let r = await applyPass(editModel.value)
  loadData()
  // if(editModel.value.amount<selectNum.value){
  //   let r = await applyPass(editModel.value)
  //   loadData()
  // }else{
  //   alert("库存余量不足！")
  // }
  }

const ids = ref([]);
// 批量同意
/** 行checkbox 选中事件 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
    console.log("ids.value",ids.value);
}
function check(row,index){
  // console.log("tttt",this.$refs.multipleTable.selection);
  if(row.flag== 1){
    return true
  }return false;
}
function handleApprove(row) {
  const applyIds = row.id || ids.value;
  proxy.$modal.confirm('确认同意？').then(function () {
    console.log("ids",ids.value.id);
    return applyPassBatch(applyIds);
  }).then(() => {
    loadData();
    proxy.$modal.msgSuccess("批量同意成功");
  }).catch(() => { });
};

// 退回
const returnApply = async (row) => {
  editModel.value.product = row.product;
  editModel.value.batchid = row.batchid;
  editModel.value.amount = row.amount;
  editModel.value.id = row.id
  editModel.value.flag = 2
  let r = await applyUpdate(editModel.value)
  loadData()
}


// 搜索
const showSearch = ref(true);

/** 重置按钮操作 */
function resetQuery() {
  // proxy.resetForm("queryRef");
  param.value.product = '',
  param.value.flag = ''
  loadData()
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("applyTake/export", {
    ...param.value
  }, `审批列表_${new Date().getTime()}.xlsx`);
}


</script>
<template>
  <el-card class="page-container">

    <!-- 筛选 -->
    <el-form inline>
      <el-form :inline="true" :model="param" v-show="showSearch">
        <el-form-item label="商品名称" prop="product">           
            <el-select placeholder="请选择商品名称" v-model="param.product" style="width: 100%">
            <el-option
              v-for="item in allProducts"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审批状态" prop="status">
                  <el-select                     
                     placeholder="审批状态"
                     clearable
                     style="width: 240px"
                     v-model="param.flag"
                  >
                  <el-option
                    v-for="item in [
                      { label: '已通过', value: 0 },
                      { label: '未审批', value: 1 }
                    ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
                  </el-select>
               </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="loadData"> <span class="iconfont icon-sousuo"></span>搜索 </el-button>
          <el-button type="default" icon="Refresh" @click="resetQuery"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </el-form>

    <!-- 按钮组 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Check" :disabled="ids.length===0" @click="handleApprove">同意</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </el-col>
    </el-row>
    <!-- 按钮组 -->
    <!-- 表格 -->
    <el-table :data="tableData" :border="true" @selection-change="handleSelectionChange">
      <el-table-column type="selection" :selectable="check" align="center" fixed="left" ></el-table-column>
      <el-table-column label="序号" width="60" type="index" align="center">
        <!-- 序号重新计算 -->
        <template #default="scope">
          <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="productname" align="center"></el-table-column>
      <el-table-column label="商品批次" prop="batchname" align="center"></el-table-column>
      <el-table-column label="数量" prop="amount" align="center" width="60px"></el-table-column>
      <el-table-column label="申请人" prop="name" align="center" width="80px"></el-table-column>
      <el-table-column label="审批状态" prop="flag" align="center">
        <template #default="scoped">
          <el-tag type="success" v-if="scoped.row.flag === 0">已通过</el-tag>
          <el-tag type="warning" v-else-if="scoped.row.flag === 1">未审批</el-tag>
          <el-tag type="warning" v-else-if="scoped.row.flag === 2">未通过</el-tag>
          <el-tag type="danger" v-else>已撤回</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审批通过时间" prop="passTime" align="center"></el-table-column>
      <el-table-column label="操作" align="center" width="130" fixed="right">
        <template #default="{ row }">
          <el-button :icon="Edit" type="primary" v-if="row.flag==1" link size="small" @click="showDialog(row)">
            <span class="iconfont icon-bianji"></span>同意
          </el-button>
          <el-button :icon="Edit" type="primary" v-if="row.flag==1" link size="small" @click="returnApply(row)">
            <span class="iconfont icon-bianji"></span>驳回
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格 -->
    <!-- 分页 -->
    <el-pagination 
      v-model:current-page="param.pageNumber" 
      v-model:page-size="param.pageSize" 
      :page-sizes="[10, 20, 30, 40]"
      layout="jumper, total, sizes, prev, pager, next" 
      background 
      :total="total" 
      @size-change="loadData"
      @current-change="loadData" 
      style="margin-top: 20px; justify-content: flex-end" />
    <!-- 分页 -->
  </el-card>
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .mb8 {
    margin-bottom: 8px;
  }
}
</style>